package com.phf.controller.front;

import com.phf.service.BookService;
import com.phf.vo.Cart;
import com.phf.vo.CartItem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.util.Map;

@Controller
@RequestMapping("front/cart")
public class CartController {
    @Autowired
    private BookService bookService;

    @RequestMapping("addCart")
    public String addCart(Integer id, HttpSession session){
        Cart cart = (Cart) session.getAttribute("cart");
        if(cart == null){
            cart = new Cart();
            session.setAttribute("cart",cart);
        }

        Map<Integer, CartItem> items = cart.getItems();
        if(items.containsKey(id)){
            CartItem item = items.get(id);
            item.setCount(item.getCount()+1);
        }else{
            CartItem item = new CartItem();
            item.setCount(1);
            item.setBook(bookService.showOneBook(id));
            items.put(id,item);
        }

        return "redirect:/front/cart/cart.jsp";
    }

    @RequestMapping("increaseCart")
    public String increaseCart(Integer id,HttpSession session){
        Cart cart = (Cart)session.getAttribute("cart");
        Map<Integer, CartItem> items = cart.getItems();
        CartItem item = items.get(id);
        item.setCount(item.getCount()+1);
        return "redirect:/front/cart/cart.jsp";
    }

    @RequestMapping("decreaseCart")
    public String decreaseCart(Integer id,HttpSession session){
        Cart cart = (Cart)session.getAttribute("cart");
        Map<Integer, CartItem> items = cart.getItems();
        CartItem item = items.get(id);
        item.setCount(item.getCount()-1);
        if(item.getCount() <= 0){
            items.remove(id);
        }
        return "redirect:/front/cart/cart.jsp";
    }

    @RequestMapping("removeCart")
    public String removeCart(Integer id,HttpSession session){
        Cart cart = (Cart)session.getAttribute("cart");
        Map<Integer, CartItem> items = cart.getItems();
        items.remove(id);
        return "redirect:/front/cart/cart.jsp";
    }

}
